import json
import time
from getSnmpInfo import getSysInfo, getSysUpTime, getProtocolInfo, getAtInfo, getIfSpeed, \
    getIfInfo, getErrPercent
import getSnmpInfo, setting
import os
from database import createTable,saveAll

def initFiles():
    for root, dirs, files in os.walk('./json_data'):
        for file in files:
            open('./json_data/' + file, 'w').close()


def update(currentTime):
    updateProtocolInfo()
    updateAtInfo()
    updateAvailability()
    updateErrPercent()
    updateChartData(currentTime)
    # print(getSnmpInfo.dataBaseInfo)

    saveAll(getSnmpInfo.dataBaseInfo)
    getSnmpInfo.dataBaseInfo = {}
    print(getSnmpInfo.dataBaseInfo)


def updateSysUpTime():
    jsonFile = open("./json_data/switchInfo.json", "r", encoding='utf-8')
    data = json.load(jsonFile)
    jsonFile.close()
    data['sysUpTime'] = getSysUpTime()
    writeJsonFile(data, 'switchInfo')


def updateSysInfo():
    writeJsonFile(getSysInfo(), 'switchInfo')


def updateProtocolInfo():
    writeJsonFile(getProtocolInfo(), 'protocolInfo')


def updateAtInfo():
    writeJsonFile(getAtInfo(), 'atInfo')

# 使用前后两次轮询时信息，计算各端口利用率
def updateAvailability():
    currentIfInfo = getIfInfo()
    preIfInfo = getSnmpInfo.preIfInfo
    ifResult = []

    for i in range(0, 28):
        info = {}
        pre = preIfInfo[i]
        cur = currentIfInfo[i]
        speed = int(setting.speedList[i][1])
        info['interface'] = i + 1
        info['InOctets'] = cur['InOctets'] - pre['InOctets']
        info['OutOctets'] = cur['OutOctets'] - pre['OutOctets']
        info['speed'] = int(speed / 1000000)
        ava = (info['InOctets'] + info['OutOctets']) * 8 / 5
        if speed != 0:
            availability = ava / speed
            getSnmpInfo.dataBaseInfo['portList'][i]['availability'] = round(availability, 2)
            info['availability'] = '{:.2%}'.format(availability)
        else:
            getSnmpInfo.dataBaseInfo['portList'][i]['availability'] = 0.00
            info['availability'] = '0.00%'
        ifResult.append(info)

    getSnmpInfo.preIfInfo = currentIfInfo
    writeJsonFile({'ifResult': ifResult}, 'Availability')


def updateErrPercent():
    currentErrPer = getErrPercent()
    preErrPer = getSnmpInfo.preErrPercent
    for i in range(0, len(preErrPer)):
        currentErrPer[i]['newInErrors'] = currentErrPer[i]['ifInErrors'] - preErrPer[i]['ifInErrors']
        currentErrPer[i]['newOutErrors'] = currentErrPer[i]['ifOutErrors'] - preErrPer[i]['ifOutErrors']
    getSnmpInfo.preErrPercent = currentErrPer
    writeJsonFile({'ifResult': currentErrPer}, 'ErrPercent')


def updateChartData(currentTime):
    curTime = time.strftime("%H:%M:%S", time.localtime(currentTime))
    jsonFile = open("./json_data/chartData.json", "r", encoding='utf-8')
    avail = open('./json_data/Availability.json', 'r', encoding='utf-8')
    err = open('./json_data/ErrPercent.json', 'r', encoding='utf-8')
    avail_json = json.load(avail)
    err_json = json.load(err)
    result = {}
    try:
        result = json.load(jsonFile)
        timeAxis = result['timeAxis']
        data = result['data']
        if len(timeAxis) >= 12:
            timeAxis.pop(0)
        timeAxis.append(curTime)
        count = 0
        for info in data:
            if len(info['receiveByte']) >= 12:
                info['receiveByte'].pop(0)
                info['sendByte'].pop(0)
                info['newInErrors'].pop(0)
                info['newOutErrors'].pop(0)
            info['receiveByte'].append([curTime, avail_json['ifResult'][count]['InOctets'] / 5000])
            info['sendByte'].append([curTime, avail_json['ifResult'][count]['OutOctets'] / 5000])
            info['newInErrors'].append([curTime, err_json['ifResult'][count]['newInErrors']])
            info['newOutErrors'].append([curTime, err_json['ifResult'][count]['newOutErrors']])
            count += 1

        result['data'] = data
        result['timeAxis'] = timeAxis
    except:
        timeAxis = []
        data = []
        timeAxis.append(curTime)
        for i in range(0, 28):
            info = {}
            info['interface'] = i + 1
            info['receiveByte'] = [[curTime, avail_json['ifResult'][i]['InOctets'] / 5000]]
            info['sendByte'] = [[curTime, avail_json['ifResult'][i]['OutOctets'] / 5000]]
            info['newInErrors'] = [[curTime, err_json['ifResult'][i]['newInErrors']]]
            info['newOutErrors'] = [[curTime, err_json['ifResult'][i]['newOutErrors']]]
            data.append(info)
        result['data'] = data
        result['timeAxis'] = timeAxis

    jsonFile.close()
    writeJsonFile(result, 'chartData')
    # print(data)


def writeJsonFile(result, fileName):
    json_str = json.dumps(result, indent=4)
    with open('./json_data/{}.json'.format(fileName), 'w') as json_file:
        json_file.write(json_str)
    json_file.close()


if __name__ == '__main__':
    createTable()
    initFiles()
    preShortTime = preLongTime = 0
    getIfSpeed()

    getSnmpInfo.preIfInfo = getIfInfo()
    getSnmpInfo.preErrPercent = getErrPercent()
    # print(getSnmpInfo.preIfInfo)
    getSnmpInfo.dataBaseInfo = {}
    while True:
        time.sleep(0.5)
        currentTime = time.time()
        if currentTime - preLongTime >= 60:
            preShortTime = preLongTime = currentTime
            updateSysInfo()
            update(currentTime)
            print('大间隔')
        elif currentTime - preShortTime >= 5:
            preShortTime = currentTime
            updateSysUpTime()
            update(currentTime)
            print('小间隔')
